<?php
/**
 * Created by PhpStorm.
 *
 * @Date: 2018-01-15
 * @Time: 15:23
 * @Author: cdkay
 * @Email: network@iyuanma.net
 *
 * @File： SpecialArticle.php
 */
namespace app\api\model\special;
use app\api\controller\News;
use app\common\model\teacher\Teacher;
use think\Db;
use think\Model;

class SpecialArticle extends Model {
    protected $table = 'teacher_essay';
    protected $pk = 'id';

    /**
     * totalArticle
     * 统计单个专栏栏目文章总数
     *
     * @author zhengkai
     * @date 2018-01-16
     *
     * @param int $scid 专栏栏目id
     * @return int|string
     */
    public static function totalArticle($scid)
    {
        $data = self::where('special_column_id', $scid)
            ->where('hide=false')
            ->count('id');

        return $data;
    }

    /**
     * getArticle
     * 获取单个专栏栏目文章数据
     *
     * @author zhengkai
     * @date 2018-01-16
     *
     * @param int $scid 专栏栏目id
     * @param int $page 当前页数
     * @param int $limit 每页获取数据条数
     * @return array
     */
    public function getArticle($scid, $page=1, $limit=10)
    {
        $data = $this::all(function($query) use (&$scid, &$page, &$limit) {
            $query->field('id, title, cover, created, special_column_id as article_column, summary')
                ->where('special_column_id', $scid)
                ->where('hide=false')
                ->order('created desc')
                ->page($page, $limit);
        });

        if (empty($data)) return [];

        $result = [];
        foreach ($data as &$val) {
            $val->created = tranTime(strtotime($val->created));

            $result[] = $val->getData();
        }

        return $result;
    }

    /**
     * getRelatedArticle
     * 获取单个专栏相关文章数据
     * @todo 暂时取的当前文章专栏的其他文章
     *
     * @param int $scid 专栏id
     * @param int $aid 当前文章id(要排除的文章)
     * @param int $limit
     * @return SpecialArticle[]|false
     * @throws \think\exception\DbException
     */
    public static function getRelatedArticle($scid, $aid, $limit=5)
    {
        $data = self::all(function ($query) use ($scid, $aid, $limit) {
            $query->alias('art');
            $query->join('teacher t', 'art.teacher_id=t.id', 'left');
            $query->where('art.special_column_id', $scid);
            $query->where('art.id', '<>', $aid);
            $query->where('art.hide=false');
            $query->field('
            art.id,
            art.title,
            art.created,
            art.summary,
            t.id as teacher_id,
            t.realname as teacher_realname,
            t.avatar as teacher_avatar
            ');
            $query->order('art.created desc');
            $query->limit($limit);
        });

        foreach ($data as &$val) {
            $val['created'] = tranTime(strtotime($val['created']));
            $val['teacher_avatar'] = $val['teacher_avatar']?:Teacher::DEFAULT_AVATAR;
        }

        return $data;
    }

    /**
     * getSingleArticle
     * 获取单个文章详情数据
     *
     * @author zhengkai
     * @date 2018-01-16
     *
     * @param int $aid 文章id
     * @param bool $loadByUrl
     * @return null|static
     */
    public function getSingleArticle($aid, $loadByUrl = false)
    {
        $data = $this::get(function($query) use ($aid, $loadByUrl){
            $query->field('id, special_column_id, title, cover, summary, created' . ($loadByUrl ? '' : ',attachment,content'))
                ->where('id', $aid)
            ;
        });

        if ($data) {
            $data->summary = stripHtml($data->summary);

            if (isset($data->attachment) && is_string($data->attachment)) {
                $attachment = json_decode($data->attachment);
                $attachment->has_audio = isset($attachment->audio);
                $attachment->has_video = isset($attachment->video);
                $data->attachment = $attachment;
            }

            if (empty($data->attachment)) $data->attachment = new \stdClass();
            $model=new News();
            $data->next=$model->getNext(['special_column_id'=>$data->special_column_id,'hide'=>'false','created'=>['<',$data->created]]);
            $data->created = tranTime(strtotime($data->created));
        }

        return $data;
    }

    public static function checkLiked($uid, $id) {
        $sql = 'select exists(SELECT 1 FROM user_essay_liked WHERE essay_id=:id AND userid=:uid) AS liked';
        $re = Db::query($sql,['uid'=>$uid,'id'=>$id]);
        return $re[0]['liked'] ?? false;
    }

    public static function articleUrl($id, $uid = null, $token = null) {
        $url = config('server.host') . '/site/share/column_essay_detail?id='.$id;
        if ($uid) $url .= '&uid='.$uid;
        if ($token) $url .= '&token='.$token;
        return $url;
    }

    public static function shareUrl($columnId, $article) {
        $isFree = SpecialColumn::is_free($columnId);
        if ($isFree){
            $url = sprintf('%s/alreadyBuyArticle?id=%d&articleColumn=%d',config('server.wapHost'),$article['id'],$article['special_column_id']);
            // $url = sprintf('%s/#/alreadyBuyArticle?id=%d&articleColumn=%d',config('server.wapHost'),$article['id'],$article['special_column_id']);
        } else {
            $url = sprintf('%s/notBuyArticle?id=%d&articleColumn=%d',config('server.wapHost'),$article['id'],$article['special_column_id']);
            // $url = sprintf('%s/#/notBuyArticle?id=%d&articleColumn=%d',config('server.wapHost'),$article['id'],$article['special_column_id']);
        }
        return $url;
    }
}